import api from './api';

interface LoginParams {
  username: string;
  password: string;
}

interface RegisterParams {
  username: string;
  password: string;
  email: string;
  phone?: string;
}

interface AuthResponse {
  token: string;
  user: {
    id: number;
    username: string;
    email: string;
  };
}

// Define the mock user interface
interface MockUser {
  id: number;
  username: string;
  password: string;
  email: string;
  phone?: string;
}

// Mock user data
const mockUsers: MockUser[] = [
  {
    id: 1,
    username: 'user1',
    password: 'password123',
    email: 'user1@example.com',
    phone: '13800138000',
  },
];

// Mock implementation using local data
export const login = async (params: LoginParams): Promise<AuthResponse> => {
  // Simulate API delay
  await new Promise(resolve => setTimeout(resolve, 800));
  
  const { username, password } = params;
  
  // Find user
  const user = mockUsers.find(u => u.username === username);
  
  if (!user || user.password !== password) {
    throw new Error('Invalid username or password');
  }
  
  // Generate mock token
  const token = `mock-token-${Date.now()}`;
  
  return {
    token,
    user: {
      id: user.id,
      username: user.username,
      email: user.email,
    },
  };
};

export const register = async (params: RegisterParams): Promise<AuthResponse> => {
  // Simulate API delay
  await new Promise(resolve => setTimeout(resolve, 1000));
  
  const { username, password, email, phone } = params;
  
  // Check if username already exists
  if (mockUsers.some(u => u.username === username)) {
    throw new Error('Username already exists');
  }
  
  // Check if email already exists
  if (mockUsers.some(u => u.email === email)) {
    throw new Error('Email already exists');
  }
  
  // Create new user
  const newUser: MockUser = {
    id: mockUsers.length + 1,
    username,
    password,
    email,
    phone,
  };
  
  // Add to mock users (in a real app, this would be done on the server)
  mockUsers.push(newUser);
  
  // Generate mock token
  const token = `mock-token-${Date.now()}`;
  
  return {
    token,
    user: {
      id: newUser.id,
      username: newUser.username,
      email: newUser.email,
    },
  };
};

export const logout = (): void => {
  localStorage.removeItem('token');
  localStorage.removeItem('user');
};

export const getCurrentUser = (): any => {
  const userStr = localStorage.getItem('user');
  if (userStr) {
    return JSON.parse(userStr);
  }
  return null;
}; 